package com.breachwalls.mogen.plugin.generator;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;

import com.breachwalls.mogen.generator.FreeMarkerModelGenerator;
import com.breachwalls.mogen.generator.ModelGenerationException;
import com.breachwalls.mogen.generator.ModelGenerator;

public class ModelGeneratorRunnableWithProgress implements IRunnableWithProgress {

    private EclipseModelGeneratorConfigurer configurer;

    public ModelGeneratorRunnableWithProgress(EclipseModelGeneratorConfigurer newConfigurer) {
        this.configurer = newConfigurer;
    }

    public void run(final IProgressMonitor monitor) throws InvocationTargetException,
            InterruptedException {
        final int alltimes = 10;
        monitor.beginTask("Model Generation...", alltimes);

        monitor.subTask("Initialized...");
        monitor.worked(2);

        EclipseModelGeneratorProperties properties = new EclipseModelGeneratorProperties(configurer);
        ModelGenerator generator = new FreeMarkerModelGenerator(properties);

        try {
            monitor.subTask("Generation...");
            monitor.worked(2);

            generator.generate();

            monitor.subTask("Building...");
            monitor.worked(5);

            IProject project = configurer.getProject();
            project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
        } catch (ModelGenerationException e) {
            throw new InvocationTargetException(e);
        } catch (Exception e) {
            throw new InvocationTargetException(e);
        }

        monitor.worked(alltimes);
        monitor.done();
    }

    protected void findFtlTemplates(final IProject project) {
        // IJavaProject java = JavaCore.create(project);
        // try {
        // IClasspathEntry[] entries = java.getResolvedClasspath(true);
        // for (IClasspathEntry entry : entries) {
        // // TODO プラグイン自身から取得できるようにしないと意味がない
        // }
        // } catch (JavaModelException e) {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }
    }

}
